package com.netdisk.controller;

import cn.hutool.core.io.FileUtil;
import com.netdisk.dto.FileDTO;
import com.netdisk.service.FileService;
import com.netdisk.service.UserActivityService;
import com.netdisk.vo.PageResult;
import com.netdisk.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件控制器
 */
@Api(tags = "文件管理")
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;
    
    @Autowired
    private UserActivityService userActivityService;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Result<FileDTO> uploadFile(
            @ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            HttpServletRequest request) {
        FileDTO fileDTO = fileService.uploadFile(file, userId);
        
        // 记录上传文件活动
        try {
            userActivityService.recordActivity(
                userId, 
                fileDTO.getId(), 
                fileDTO.getName(), 
                "upload", 
                "上传了文件 \"" + fileDTO.getName() + "\"",
                request.getRemoteAddr(),
                request.getHeader("User-Agent")
            );
        } catch (Exception e) {
            // 记录活动失败，但不影响上传功能
            System.err.println("Failed to record activity: " + e.getMessage());
        }
        
        return Result.success("上传成功", fileDTO);
    }

    @ApiOperation("获取文件信息")
    @GetMapping("/info")
    public Result<FileDTO> getFileInfo(
            @ApiParam(value = "文件ID", required = true) @RequestParam("fileId") Integer fileId,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId) {
        FileDTO fileDTO = fileService.getFileInfo(fileId, userId);
        return Result.success(fileDTO);
    }

    @ApiOperation("获取文件列表")
    @GetMapping("/list")
    public Result<PageResult<FileDTO>> listFiles(
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @ApiParam(value = "每页大小", defaultValue = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @ApiParam(value = "搜索关键词", required = false) @RequestParam(value = "query", required = false, defaultValue = "") String query) {
        try {
            System.out.println("Controller: Listing files for user: " + userId + ", page: " + page + ", pageSize: " + pageSize + ", query: " + query);
            
            // 调用服务获取文件列表
            PageResult<FileDTO> pageResult = fileService.listUserFiles(userId, page, pageSize, query);
            
            // 检查是否有已删除的文件
            if (pageResult != null && pageResult.getItems() != null) {
                System.out.println("Controller received " + pageResult.getItems().size() + " files");
                
                long deletedCount = pageResult.getItems().stream()
                        .filter(file -> file.getDeletedAt() != null)
                        .count();
                
                if (deletedCount > 0) {
                    System.out.println("WARNING: Controller found " + deletedCount + " files with deletedAt not null");
                    
                    // 手动过滤掉已删除的文件
                    List<FileDTO> filteredFiles = pageResult.getItems().stream()
                            .filter(file -> file.getDeletedAt() == null)
                            .collect(Collectors.toList());
                    
                    // 更新结果
                    pageResult = new PageResult<>(pageResult.getTotal() - deletedCount, filteredFiles);
                    System.out.println("After filtering: " + filteredFiles.size() + " files");
                }
            }
            
            return Result.success(pageResult);
        } catch (Exception e) {
            System.err.println("Error in listFiles controller: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取文件列表失败: " + e.getMessage());
        }
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/delete")
    public Result<Void> deleteFile(
            @ApiParam(value = "文件ID", required = true) @RequestParam("fileId") Integer fileId,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            HttpServletRequest request) {
        try {
            System.out.println("Controller: Moving file to trash: fileId=" + fileId + ", userId=" + userId);
            
            // 先获取文件信息，用于记录活动日志
            FileDTO fileDTO = fileService.getFileInfo(fileId, userId);
            
            boolean result = fileService.deleteFile(fileId, userId);
            
            if (result) {
                // 记录删除文件活动
                try {
                    userActivityService.recordActivity(
                        userId, 
                        fileId, 
                        fileDTO.getName(), 
                        "delete", 
                        "将文件 \"" + fileDTO.getName() + "\" 移至回收站",
                        request.getRemoteAddr(),
                        request.getHeader("User-Agent")
                    );
                } catch (Exception e) {
                    // 记录活动失败，但不影响删除功能
                    System.err.println("Failed to record activity: " + e.getMessage());
                }
                
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            System.err.println("Controller error: " + e.getMessage());
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("重命名文件")
    @PutMapping("/rename")
    public Result<FileDTO> renameFile(
            @ApiParam(value = "文件ID", required = true) @RequestParam("fileId") Integer fileId,
            @ApiParam(value = "新文件名", required = true) @RequestParam("newName") String newName,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            HttpServletRequest request) {
        
        // 先获取原文件名
        FileDTO oldFileDTO = fileService.getFileInfo(fileId, userId);
        String oldFileName = oldFileDTO.getName();
        
        FileDTO fileDTO = fileService.renameFile(fileId, newName, userId);
        
        // 记录重命名文件活动
        userActivityService.recordActivity(
            userId, 
            fileId, 
            fileDTO.getName(), 
            "rename", 
            "将文件 \"" + oldFileName + "\" 重命名为 \"" + newName + "\"",
            request.getRemoteAddr(),
            request.getHeader("User-Agent")
        );
        
        return Result.success("重命名成功", fileDTO);
    }

    @ApiOperation("下载文件")
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(
            @ApiParam(value = "文件ID", required = true) @RequestParam("fileId") Integer fileId,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            @ApiParam(value = "是否预览", required = false) @RequestParam(value = "preview", required = false, defaultValue = "false") Boolean preview,
            HttpServletRequest request) throws IOException {
        // 获取文件路径
        String filePath = fileService.downloadFile(fileId, userId);
        
        // 获取文件信息
        FileDTO fileDTO = fileService.getFileInfo(fileId, userId);
        String fileName = fileDTO.getName();
        
        // 如果不是预览，记录下载活动
        if (!preview) {
            userActivityService.recordActivity(
                userId, 
                fileId, 
                fileName, 
                "download", 
                "下载了文件 \"" + fileName + "\"",
                request.getRemoteAddr(),
                request.getHeader("User-Agent")
            );
        }
        
        // 读取文件内容
        byte[] fileContent = FileUtil.readBytes(filePath);
        
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        
        // 根据文件类型设置Content-Type
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        
        if (preview) {
            // 如果是预览模式，设置相应的Content-Type
            switch (fileExtension) {
                case "pdf":
                    headers.setContentType(MediaType.APPLICATION_PDF);
                    break;
                case "jpg":
                case "jpeg":
                    headers.setContentType(MediaType.IMAGE_JPEG);
                    break;
                case "png":
                    headers.setContentType(MediaType.IMAGE_PNG);
                    break;
                case "gif":
                    headers.setContentType(MediaType.IMAGE_GIF);
                    break;
                case "txt":
                case "csv":
                    headers.setContentType(MediaType.TEXT_PLAIN);
                    break;
                case "html":
                    headers.setContentType(MediaType.TEXT_HTML);
                    break;
                case "xml":
                    headers.setContentType(MediaType.TEXT_XML);
                    break;
                case "mp4":
                    headers.setContentType(MediaType.parseMediaType("video/mp4"));
                    break;
                case "mp3":
                    headers.setContentType(MediaType.parseMediaType("audio/mp3"));
                    break;
                case "doc":
                case "docx":
                    headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
                    break;
                case "xls":
                case "xlsx":
                    headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                    break;
                case "ppt":
                case "pptx":
                    headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.presentationml.presentation"));
                    break;
                default:
                    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
                    break;
            }
        } else {
            // 下载模式，强制下载
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        }
        
        // 返回文件内容
        return ResponseEntity.ok()
                .headers(headers)
                .body(fileContent);
    }
} 